package com.changgou.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.EsManagerMapper;
import com.changgou.search.service.EsManagerService;
import com.changgou.goods.feign.SkuFeign;
import com.service.search.pojo.SkuInfo;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class EsManagerServiceImpl implements EsManagerService {
    @Autowired
        private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private EsManagerMapper esManagerMapper;
    @Override
    public void creatIndexAndMapping() {
        elasticsearchTemplate.createIndex(SkuInfo.class);
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {
        List<Sku> skuList = skuFeign.findSkuListBySpuId("all");
        if (skuList.size()<=0||skuList==null){
            throw new RuntimeException("当前没有数据，无法查询0");
        }
        String jsonStringSkuList = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfoList  = JSON.parseArray(jsonStringSkuList, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfoList);
    }

    @Override
    public void importDataToEsBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if (skuList.size()<=0||skuList==null){
            throw new RuntimeException("当前没有数据，无法查询");
        }

        String jsonStringSkuList = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfoList  = JSON.parseArray(jsonStringSkuList, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfoList);
    }

    @Override
    public void deleteBySpuId(String spuId) {
        Iterable<SkuInfo> iterable = esManagerMapper.search(QueryBuilders.termQuery("spuId", spuId));
        if (iterable == null) {
            throw new RuntimeException("当前没有数据，无法查询");
        }
        esManagerMapper.deleteAll(iterable);
    }
}
